<?php

namespace App\Admin\Actions\Good;

use App\Admin\Services\GoodService;
use App\Jobs\DownImageJob;
use App\Jobs\ImportAsinJob;
use App\Model\ExportGoodJob;
use App\Model\ExportGoodJobDetail;
use App\Model\ImportJob;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ImportAsin extends Action
{
    public $name = '导入商品Asin数据';

    protected $selector = '.import-asin-post';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return Response
     * @throws IOException
     * @throws ReaderNotOpenedException
     */
    public function handle(Request $request)
    {
        $reader = ReaderEntityFactory::createCSVReader();
        $reader->open($request->file('file'));

        $sheets = $reader->getSheetIterator();
        $sheets->rewind();
        $sheet = $sheets->current();

        $data = [];

        foreach ($sheet->getRowIterator() as $k => $row) {

            if ($k == 0) {
                continue;
            }
            $temp = $row->toArray();
            if (count($temp) >= 8) {
                $data[] = $temp;
            }

        }
        $reader->close(); // 释放内存

        //去除表头
        $total = count($data) - 1;

        if (!$total) {

            return $this->response()->info('未发现可导入数据')->refresh();

        }

        $job = ImportJob::query()->create([
            'operator_id' => Admin::user()->id,
            'total' => $total
        ]);
        if ($job) {
            foreach ($data as $k => $row) {
                if ($k == 0) {
                    continue;
                }
                if (strlen($row[8])) {
                    $row[8] = GoodService::convertToUtf($row[8]);
                }

                dispatch(new ImportAsinJob($job->id, $k, $row));
            }
        }

        return $this->response()->success('正在处理中请稍后，查看')->refresh();
    }

    public function form()
    {
        $this->file('file', '请导入Asin数据')->rules('required', [
            'required' => '请上传Asin的csv文件'
        ]);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-asin-post"><i class="fa fa-upload"></i>导入Asin</a>
HTML;
    }

}
